<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="零件编号" prop="partNumber">
        <el-input
          v-model="queryParams.partNumber"
          placeholder="请输入零件编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="零件名称" prop="partName">
        <el-input
          v-model="queryParams.partName"
          placeholder="请输入零件名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="分类编号" prop="categoryId">
        <el-input
          v-model="queryParams.categoryId"
          placeholder="请输入分类编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['neo:part:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAddLink"
          v-hasPermi="['neo:part:addLink']"
        >新增联系</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['neo:part:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['neo:part:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['neo:part:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="partList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="零件id"
       align="center" prop="partId" />
      <el-table-column label="零件编号" align="center" prop="partNumber" />
      <el-table-column label="零件名称" align="center" prop="partName" />
      <el-table-column label="分类编号" align="center" prop="categoryId" />
      <el-table-column label="零件描述" align="center" prop="description" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['neo:part:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['neo:part:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改零件信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="零件编号" prop="partNumber">
          <el-input v-model="form.partNumber" placeholder="请输入零件编号" />
        </el-form-item>
        <el-form-item label="零件名称" prop="partName">
          <el-input v-model="form.partName" placeholder="请输入零件名称" />
        </el-form-item>
        <el-form-item label="分类编号" prop="categoryId">
          <el-input v-model="form.categoryId" placeholder="请输入分类编号" />
        </el-form-item>
        <el-form-item label="零件描述" prop="description">
          <el-input v-model="form.description" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 添加联系 -->
    <el-dialog title="新增联系" :visible.sync="linkOpen" width="500px" append-to-body>
  <el-form ref="linkForm" :model="linkForm" :rules="linkRules" label-width="80px">
    <el-form-item label="零件名字" prop="partName">
      <el-select v-model="linkForm.partName" placeholder="请选择零件名称">
    <el-option
      v-for="name in partNames"
      :key="name"
      :label="name"
      :value="name"
    />
  </el-select>
    </el-form-item>
    <el-form-item label="分类名字" prop="categoryName">
      <el-select v-model="linkForm.categoryName" placeholder="请选择分类名字">
        <el-option
          v-for="name in categoryNames"
          :key="name"
          :label="name"
          :value="name"
        />
      </el-select>
    </el-form-item>
  </el-form>
  <div slot="footer" class="dialog-footer">
    <el-button type="primary" @click="submitLinkForm">确 定</el-button>
    <el-button @click="linkOpen = false">取 消</el-button>
  </div>
</el-dialog>
  </div>
</template>

<script>
import { listPart, getPart, delPart, addPart, updatePart ,addPartCategoryLink} from "@/api/neo/part";
import { listPartCategory} from "@/api/neo/partCategory";
export default {
  name: "Part",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 零件信息表格数据
      partList: [],
       // 零件分类表格数据
       partCategoryList: [],
      partNames: [], // 存储所有零件名称
      categoryNames: [], // 存储所有分类名称
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 新增联系对话框显示状态
    linkOpen: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        partNumber: null,
        partName: null,
        categoryId: null,
        description: null,
      },
      // 表单参数
      form: {},
      // 新增联系表单数据
    linkForm: {
      partName: null,
      categoryName: null,
    },
      // 表单校验
      rules: {
      },
      // 新增联系表单校验规则
    linkRules: {
      partName: [{ required: true, message: "零件名字不能为空", trigger: "blur" }],
      categoryName: [{ required: true, message: "分类名字不能为空", trigger: "blur" }],
    }
    };
  },
  created() {
    this.getList();
    this.fetchPartNames(); // 获取所有零件名称
    this.fetchCategoryNames(); // 获取所有分类名称
  },
  methods: {
    /** 查询零件分类列表 */
    getCategoryList() {
      this.loading = true;
      listPartCategory(this.queryParams).then(response => {
        this.partCategoryList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
      console.log(this.partCategoryList);
    },
    // 获取所有分类名称
  fetchCategoryNames() {
    listPartCategory({ pageNum: 1, pageSize: 1000 }) // 假设 API 支持分页查询
      .then(response => {
        this.categoryNames = response.rows.map(partCategory => partCategory.categoryName);
      })
      .catch(error => {
        console.error("获取分类名称失败", error);
      });
  },
    fetchPartNames() {
    listPart({ pageNum: 1, pageSize: 1000 }) // 假设 API 支持分页查询
      .then(response => {
        this.partNames = response.rows.map(part => part.partName);
      })
      .catch(error => {
        console.error("获取零件名称失败", error);
      });
  },
    handleAddLink() {
    this.linkOpen = true;
    this.resetLinkForm();
  },
  resetLinkForm() {
    this.linkForm = {
      partId: null,
      categoryId: null,
    };
    this.resetForm("linkForm");
  },
   /** 提交新增联系表单 */
   submitLinkForm() {
    this.$refs["linkForm"].validate(valid => {
      if (valid) {
        // 调用API建立零件与分类的关联
        addPartCategoryLink(this.linkForm).then(response => {
          this.$modal.msgSuccess("新增联系成功");
          this.linkOpen = false;
          this.getList(); // 刷新列表
        });
      }
    });
  },
    /** 查询零件信息列表 */
    getList() {
      this.loading = true;
      listPart(this.queryParams).then(response => {
        this.partList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        partId: null,
        partNumber: null,
        partName: null,
        categoryId: null,
        description: null,
        createTime: null,
        updateTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.partId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加零件信息";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const partId = row.partId || this.ids
      getPart(partId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改零件信息";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.partId != null) {
            updatePart(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addPart(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const partNames = row.partName ? [row.partName] : this.partList
    .filter(part => this.ids.includes(part.partId))
    .map(part => part.partName);

      this.$modal.confirm('是否确认删除零件为"' + partNames + '"的数据项？').then(function() {
        return delPart(partNames);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('neo/part/export', {
        ...this.queryParams
      }, `part_${new Date().getTime()}.xlsx`)
    }

  },

};
</script>
